<script setup>
import { reactive, ref, watch } from 'vue'
import { deleteReturnReason, listReturnReasons, updateReturnReasonStatus } from '@/service/order-return-reason.js'
import { ElMessageBox, ElNotification } from 'element-plus'
import ReasonForReturnDialog from '@/pages/ReasonForReturn/components/ReasonForReturnDialog.vue'

const searchForm = reactive({
  page: 1,
  pageSize: 10,
})
const reasonList = ref([])
const totalRecords = ref(0)
const loadData = async () => {
  const res = await listReturnReasons(searchForm.page, searchForm.pageSize)
  totalRecords.value = res.data.total
  reasonList.value = res.data.records
  reasonList.value = res.data.records.map((item) => ({
    ...item,
    switchLoading: false,
  }))

  console.log(reasonList.value)
}
watch(
  searchForm,
  () => {
    loadData()
  },
  { immediate: true }
)
const type = ref('add')
const reasonForReturnDialogRef = ref()
function handleSave() {
  type.value = 'add'
  reasonForReturnDialogRef.value.showModal = true
}
function handleEditEvent(row) {
  type.value = 'edit'
  console.log(row)
  reasonForReturnDialogRef.value.reasonForm.id = row.id
  reasonForReturnDialogRef.value.reasonForm.sort = row.sort
  reasonForReturnDialogRef.value.reasonForm.name = row.name
  reasonForReturnDialogRef.value.reasonForm.status = row.status
  console.log(reasonForReturnDialogRef.value.reasonForm)
  reasonForReturnDialogRef.value.showModal = true
}
function handleDeleteEvent(row) {
  ElMessageBox.confirm(`确定删除条目：<span style="color: red">${row.name}</span>?`, '信息', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true, // 允许内容使用 HTML 字符串
  })
    .then(async () => {
      await deleteReturnReason(row.id)
      ElNotification({
        title: '提示',
        message: '成功删除条目',
        type: 'success',
      })
      await loadData()
    })
    .catch(() => {
      ElNotification({
        title: '提示',
        message: '取消删除',
        type: 'info',
      })
    })
}
function beforeChangeSwitch(row) {
  row.switchLoading = true
  return new Promise((resolve, reject) => {
    const targetStatus = row.status === 1 ? 0 : 1
    updateReturnReasonStatus(row.id, targetStatus)
      .then(() => {
        loadData()
        resolve(true)
      })
      .catch(reject(false))
      .finally(() => {
        row.switchLoading = false
      })
  })
}
</script>

<template>
  <div class="reason-for-return">
    <el-card class="config-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>订单规则设置</span>
          <el-button type="primary" @click="handleSave">添加规则</el-button>
        </div>
      </template>
      <template #default>
        <el-table
          :data="reasonList"
          :header-cell-style="() => ({ background: '#eef1f6', color: '#606266' })"
          border
          style="width: 100%"
        >
          <el-table-column align="center" label="编号">
            <template #default="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="原因类型" min-width="200">
            <template #default="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="排序">
            <template #default="scope">
              <span>{{ scope.row.sort }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否可用">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :activeValue="1"
                :before-change="() => beforeChangeSwitch(scope.row)"
                :inactive-value="0"
                :loading="scope.row.switchLoading"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" label="添加时间" min-width="170">
            <template #default="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" min-width="170">
            <template #default="scope">
              <el-button type="default" @click="handleEditEvent(scope.row)">编辑</el-button>
              <el-button type="danger" @click="handleDeleteEvent(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: flex-end; margin-top: 20px">
          <el-pagination
            v-model:current-page="searchForm.page"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :total="totalRecords"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; text-align: right"
          />
        </div>
      </template>
    </el-card>
  </div>
  <ReasonForReturnDialog ref="reasonForReturnDialogRef" :type="type" @update="loadData"></ReasonForReturnDialog>
</template>

<style lang="scss" scoped>
.reason-for-return {
  background-color: #fff;
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
  }
}
</style>
